package com.qa.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.qa.pojo.SchoolAndPosition;
import com.qa.pojo.SchoolMacInfo;
import com.qa.pojo.Users;
import com.qa.pojo.WyyCreatePojo;
import com.qa.pojo.WyyDeletePojo;
import com.qa.pojo.WyyParaent;
import com.qa.pojo.WyyStatusPojo;
import com.qa.pojo.qpy_configinfo;
import com.qa.pojo.qpy_positioninfo;
import com.qa.service.IForPushService;
import com.qa.util.PostWYY;

@Controller
@RequestMapping("/forPush")
public class ForPushController {
	@Resource
	private IForPushService forPushService;
	Logger logger = Logger.getLogger(this.getClass());

	/**
	 * 获取学校及位置
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws ServletException
	 */
	@RequestMapping("/getschoolAndPosition")
	@ResponseBody
	public Map<String, Object> getschoolAndPosition(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		response.setStatus(200);
		try {
			List<String> schools = this.forPushService.getschools();
			List<SchoolAndPosition> schoolAndPositions = this.forPushService
					.schoolAndPositions();
			if (schools != null && schools.size() > 0
					&& schoolAndPositions != null) {
				resultMap.put("tag", "success");
				resultMap.put("schools", schools);
				resultMap.put("schoolAndPositions", schoolAndPositions);
			} else {
				resultMap.put("tag", "error");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return resultMap;
	}

	/**
	 * 查询摄像头信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws ServletException
	 */
	@RequestMapping("/selectCamera")
	@ResponseBody
	public Map<String, Object> selectCamera(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		response.setStatus(200);
		try {
			/*
			 * alert("学校=" + sort + "位置" + func + "在线状态" + examineGroup +
			 * "设置状态：" + caseAscr + "功能名称：" + selectFunction + "关键字：" +
			 * selectKeyword);
			 */
			String schoolname = request.getParameter("sort").equals("null") ? null
					: URLDecoder.decode(request.getParameter("sort"), "UTF-8");
			String position = request.getParameter("func").equals("null") ? null
					: URLDecoder.decode(request.getParameter("func"), "UTF-8");
			List<String> group = request.getParameter("examineGroup") == null ? null
					: Arrays.asList(URLDecoder.decode(
							request.getParameter("examineGroup"), "UTF-8"));
			List<Integer> examineGroup = new ArrayList<Integer>();
			if (group == null || group.size() == 0
					|| group.get(0).trim().equals("")) {
				examineGroup = null;
			} else {
				for (int i = 0; i < group.get(0).split(",").length; i++) {
					examineGroup.add(Integer
							.valueOf(group.get(0).split(",")[i]));
				}
			}
			String caseAscrString = request.getParameter("caseAscr");
			int caseAscr = -1;
			if (caseAscrString.equals("person")) {
				caseAscr = 0;
			} else if (caseAscrString.equals("public")) {
				caseAscr = 1;
			} else {
				caseAscr = -1;
			}
			String selectFunction = request.getParameter("selectFunction")
					.equals("null") ? null : URLDecoder.decode(
					request.getParameter("selectFunction"), "UTF-8");
			String selectKeyword = URLDecoder.decode(
					request.getParameter("selectKeyword"), "UTF-8");
			int usersid = getUser(request).getUsersid();

			List<qpy_positioninfo> cameralInfo = this.forPushService
					.selectCameralInfo(schoolname, position, examineGroup,
							caseAscr, selectFunction, selectKeyword, usersid);
			System.out.println("abc");

			if (cameralInfo != null && cameralInfo.size() > 0) {
				resultMap.put("tag", "success");
				resultMap.put("result", cameralInfo);
			} else {
				resultMap.put("tag", "error");
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return resultMap;
	}

	/**
	 * 添加设备信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws ServletException
	 */
	@RequestMapping(value = "/insertCase", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> insertCase(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int isSuccess = 0;
		try {
			response.setStatus(200);
			qpy_configinfo qpyConfiginfos = this.forPushService
					.selectQpyConfig();
			String macInfo = URLDecoder.decode(request.getParameter("step"),
					"UTF-8");
			String json = PostWYY.postWyy("create", qpyConfiginfos, macInfo);
			System.out.println(json);
			if (json != null && !json.trim().equals("")) {
				Gson gson = new Gson();
				WyyCreatePojo createPojoInfo = gson.fromJson(json,
						WyyCreatePojo.class);
				if (createPojoInfo.getCode() == 200) {
					int setState = 0;
					String schoolname = URLDecoder.decode(
							request.getParameter("sortAdd"), "UTF-8");
					String position = URLDecoder.decode(
							request.getParameter("funcAdd"), "UTF-8");
					String ipInfo = URLDecoder.decode(
							request.getParameter("funchildname"), "UTF-8");
					String setStateInfo = URLDecoder.decode(
							request.getParameter("expectresult"), "UTF-8");
					if (setStateInfo.equals("正常")) {
						setState = 1;
					} else if (setStateInfo.equals("禁用")) {
						setState = 2;
					} else {
						setState = 0;
					}
					String remark = URLDecoder.decode(
							request.getParameter("remark"), "UTF-8");
					isSuccess = this.forPushService.insertPositionInfo(
							schoolname, position, ipInfo, macInfo, setState,
							remark, createPojoInfo.getRet().getPushUrl(),
							createPojoInfo.getRet().getRtmpPullUrl(),
							createPojoInfo.getRet().getName(), createPojoInfo
									.getRet().getCid());
				}
			}
			if (isSuccess == 1) {
				resultMap.put("tag", "success");
			} else {
				resultMap.put("tag", "error");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return resultMap;
	}

	/**
	 * 编辑设备信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws ServletException
	 */
	@RequestMapping(value = "/EditCase", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> EditCase(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		response.setStatus(200);
		try {
			int setState = 0;
			int positionid = Integer
					.valueOf(request.getParameter("editCaseId"));
			String schoolname = URLDecoder.decode(
					request.getParameter("sortEdit"), "UTF-8");
			String position = URLDecoder.decode(
					request.getParameter("funcEdit"), "UTF-8");
			String ipInfo = URLDecoder.decode(
					request.getParameter("funchildnameEdit"), "UTF-8");
			String setStateInfo = URLDecoder.decode(
					request.getParameter("expectresultEdit"), "UTF-8");
			if (setStateInfo.equals("正常")) {
				setState = 1;
			} else if (setStateInfo.equals("禁用")) {
				setState = 2;
			} else {
				setState = 0;
			}
			String macInfo = URLDecoder.decode(
					request.getParameter("stepEdit"), "UTF-8");
			String remark = URLDecoder.decode(
					request.getParameter("remarkEdit"), "UTF-8");

			int isSuccess = this.forPushService.editMacInfo(positionid,
					schoolname, position, ipInfo, setState, macInfo, remark);

			if (isSuccess == 1) {
				resultMap.put("tag", "success");
			} else {
				resultMap.put("tag", "error");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return resultMap;
	}

	/**
	 * 删除设备信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws ServletException
	 */
	@RequestMapping(value = "/deleteCase", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> deleteCase(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		response.setStatus(200);
		try {
			List<String> signGroup = request.getParameter("signGroup") == null ? null
					: Arrays.asList(URLDecoder.decode(
							request.getParameter("signGroup"), "UTF-8"));

			List<Integer> signGroupList = new ArrayList<Integer>();
			if (signGroup == null || signGroup.size() == 0
					|| signGroup.get(0).trim().equals("")) {
				signGroup = null;
			} else {
				for (int i = 0; i < signGroup.get(0).split(",").length; i++) {
					signGroupList.add(Integer.valueOf(signGroup.get(0).split(
							",")[i]));
				}
			}
			qpy_configinfo qpyConfiginfos = this.forPushService
					.selectQpyConfig();
			for (int i = 0; i < signGroupList.size(); i++) {
				String cid = this.forPushService.selectCameralCid(signGroupList
						.get(i));
				String json = PostWYY.postWyy("delete", qpyConfiginfos, cid);
				if (json != null && !json.trim().equals("")) {
					Gson gson = new Gson();
					WyyDeletePojo deletePojoInfo = gson.fromJson(json,
							WyyDeletePojo.class);
					if (deletePojoInfo.getCode() == 200) {
						logger.info("删除频道成功,频道ID：" + cid);
					} else {
						logger.error("删除频道失败,频道ID：" + cid);
					}
				}
			}
			int isSuccess = this.forPushService.deleteMacInfo(signGroupList);

			if (isSuccess > 0) {
				resultMap.put("tag", "success");
			} else {
				resultMap.put("tag", "error");
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return resultMap;
	}

	/**
	 * 获取这个学校下面所有的设备信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws ServletException
	 */

	@RequestMapping("/getSchoolMacInfo")
	@ResponseBody
	public List<SchoolMacInfo> getSchoolMacInfo(HttpServletRequest request,
			HttpServletResponse response) {
		List<SchoolMacInfo> macInfos = new ArrayList<SchoolMacInfo>();
		response.setStatus(200);
		try {
			System.out.println(request.getParameter("schoolname"));
			String schoolname = request.getParameter("schoolname") == null ? ""
					: URLDecoder.decode(request.getParameter("schoolname"),
							"UTF-8");
			System.out.println(schoolname);
			macInfos = this.forPushService
					.selectCameralInfoFromSchoolname(schoolname);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return macInfos;
	}

	/**
	 * 同步所有设备状态状态
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws ServletException
	 */
	@RequestMapping(value = "/tongbu", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> tongbu(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		response.setStatus(200);
		try {
			int isSuccess = 1;
			qpy_configinfo qpyConfiginfos = this.forPushService
					.selectQpyConfig();
			List<String> cids = this.forPushService.selectCameralCids();

			for (int i = 0; i < cids.size(); i++) {
				String json = PostWYY.postWyy("stats", qpyConfiginfos,
						cids.get(i));
				if (json != null && !json.trim().equals("")) {
					Gson gson = new Gson();
					WyyStatusPojo returnPojoInfo = gson.fromJson(json,
							WyyStatusPojo.class);
					if (returnPojoInfo.getCode() != 200) {
						isSuccess = 0;
					} else {
						int updateCount = this.forPushService
								.updateCameralStatus(cids.get(i),
										returnPojoInfo.getRet().getStatus());
						logger.info("更新状态数量为：" + updateCount);
					}
				}
			}
			if (isSuccess == 1) {
				resultMap.put("tag", "success");
			} else {
				resultMap.put("tag", "error");
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return resultMap;
	}

	/**
	 * 修改预设状态
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws ServletException
	 */
	@RequestMapping(value = "/examineCase", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> examineCase(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		response.setStatus(200);
		try {
			int isSuccess = 0;
			int positionid = Integer
					.valueOf(request.getParameter("positionid"));
			int setstate = Integer.valueOf(request.getParameter("setstate"));
			qpy_configinfo qpyConfiginfos = this.forPushService
					.selectQpyConfig();
			String cid = this.forPushService.selectCameralCid(positionid);
			// 1恢复频道，2禁用频道
			if (setstate == 1) {
				String json = PostWYY.postWyy("resume", qpyConfiginfos, cid);
				if (json != null && !json.trim().equals("")) {
					Gson gson = new Gson();
					WyyParaent returnPojoInfo = gson.fromJson(json,
							WyyParaent.class);
					if (returnPojoInfo.getCode() == 200) {
						int state = 0;
						isSuccess = this.forPushService
								.changeCameralInfoSetState(positionid, state,
										setstate);
					}
				}
			} else if (setstate == 2) {
				String json = PostWYY.postWyy("pause", qpyConfiginfos, cid);
				if (json != null && !json.trim().equals("")) {
					Gson gson = new Gson();
					WyyParaent returnPojoInfo = gson.fromJson(json,
							WyyParaent.class);
					if (returnPojoInfo.getCode() == 200) {
						int state = 2;
						isSuccess = this.forPushService
								.changeCameralInfoSetState(positionid, state,
										setstate);
					}
				}
			} else {
				logger.error("频道禁用/恢复，传递参数错误");
			}
			if (isSuccess == 1) {
				resultMap.put("tag", "success");
			} else {
				resultMap.put("tag", "error");
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return resultMap;
	}

	/**************
	 * 从session中得到用户
	 * 
	 * @param res
	 * @return
	 */
	public static Users getUser(HttpServletRequest res) {
		Users user = (Users) res.getSession().getAttribute("user");
		return user;
	}
}